package com.library.view;

import com.library.controller.BorrowController;
import com.library.controller.UserController;
import com.library.pojo.dto.borrow.BorrowPageQueryDTO;
import com.library.pojo.dto.user.UserChangePasswordDTO;
import com.library.pojo.vo.BorrowVO;
import com.library.pojo.vo.UserVO;
import com.library.result.PageResult;
import com.library.result.Result;
import com.library.entity.Pagination;
import com.library.entity.tableCol.BorrowCol;
import com.library.utils.LocalCacheUtil;
import com.library.view.components.CommonButton;
import com.library.view.components.TipDialog;
import io.yukk1o.easytermui.EasyTermUI;
import io.yukk1o.easytermui.component.Button;
import io.yukk1o.easytermui.component.InputBox;
import io.yukk1o.easytermui.component.Panel;
import io.yukk1o.easytermui.component.Text;
import io.yukk1o.easytermui.component.complex.table.Table;
import io.yukk1o.easytermui.constant.AnsiConstants;
import io.yukk1o.easytermui.util.PrintUtils;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

/**
 * 个人信息面板
 * <p>
 * 包含组件:
 * 顶部：返回按钮、个人信息标题
 * 中间：修改密码按钮、退出账号按钮
 * 底部：借阅记录列表、页码显示（当前/最大）、上下页翻页按钮
 * <p>
 * 交互流程:
 * 1. 点击返回/按ESC → 返回上一界面；
 * 2. 点击修改密码 → 进入修改密码界面；
 * 3. 点击退出账号 → 清空本地缓存，跳转登录/注册界面；
 * 4. 选中未过期/未归还的借阅记录，按Enter → 执行图书归还；
 * 5. 翻页按钮切换页码，查看更多借阅记录。
 */
public class UserInfoPanel {
    private final Pagination pagination;
    private final BorrowController borrowController;
    private final UserController userController;
    private final Panel rootPanel;
    private final EasyTermUI easyTermUI = new EasyTermUI();
    private Table dataTable;
    private BorrowPageQueryDTO borrowPageQueryDTO;
    private final Integer currentUserId = Integer.valueOf(Objects.requireNonNull(LocalCacheUtil.readFromCache("userId"))); // 当前登录用户ID（动态获取）
    private boolean init = false;

    public UserInfoPanel() {
        this.userController = new UserController();
        this.borrowController = new BorrowController();
        this.pagination = new Pagination();
        pagination.setPageSize(25);
        this.rootPanel = new Panel(0, 0, 120, 40);

        /// TODO: 对顶部栏进行封装
        // 标题文本
        Text line1 = new Text(0, 1, 120, 1, "========================================================================================================================");
        Text title = new Text(57, 3, 5, 1, "图书馆系统");
        Text line2 = new Text(0, 5, 120, 1, "========================================================================================================================");

        //分隔线
        Text line3 = new Text(0, 10, 120, 1, "------------------------------------------------------------------------------------------------------------------------");
        rootPanel.addComponent(line3);
        rootPanel.addComponent(line1);
        rootPanel.addComponent(title);
        rootPanel.addComponent(line2);

        /// 返回按钮
        CommonButton backButton = new CommonButton(1, 3, " <<<< ", ( )-> {
            easyTermUI.stop();
        });
        rootPanel.addComponent(backButton);

        /// 分开渲染
        initTop();
        initTable();

        init = true;

        /// 初始化界面
        PrintUtils.clearScreen();
        easyTermUI.init(rootPanel);
    }

    /**
     * 渲染借阅记录列表
     */
    private void initTable() {
        /// 借阅记录列表
        LinkedHashMap<String, Integer> colMeta = new LinkedHashMap<>();
        colMeta.put("编号", 8);
        colMeta.put("书名", 40);
        colMeta.put("借阅时间", 30);
        colMeta.put("归还时间", 30);
        colMeta.put("操作", 8);

        this.dataTable = new Table(0, 11, 25, colMeta);
        rootPanel.addComponent(dataTable);

        BorrowController borrowController = new BorrowController();

        /// 设置查询条件
        this.borrowPageQueryDTO = new BorrowPageQueryDTO();
        borrowPageQueryDTO.setPageSize(pagination.getPageSize());
        borrowPageQueryDTO.setUserId(currentUserId);

        refresh(1);

        /// 页码显示
        Text pageText = new Text(59, 39, 10, 1, getPageInfoText());
        rootPanel.addComponent(pageText);

        // 上下页翻页按钮
        Button prevButton = new Button(41, 39, " 上一页 ", (button) -> {
            if (pagination.prev()) {
                refresh(pagination.getCurrentPage());
                pageText.setText(getPageInfoText());
            }
        });

        rootPanel.addComponent(prevButton);
        Button nextButton = new Button(69, 39, " 下一页 ", (button -> {
            if (pagination.next()) {
                refresh(pagination.getCurrentPage());
                pageText.setText(getPageInfoText());
            }
        }));
        rootPanel.addComponent(nextButton);
    }

    /**
     * 初始化顶部
     */
    private void initTop() {

        Text idText = new Text(0, 7, 7, 1, "Id: ");
        Text nameText = new Text(10, 7, 20, 1, "用户名: ");

        Result<UserVO> userResult = userController.selectUserInfo(currentUserId);
        UserVO userData = userResult.getData();
        String username = userData.getUsername();
        nameText.setText("用户名: " + username);
        idText.setText("ID: " + userData.getUserId());

        rootPanel.addComponent(nameText);
        rootPanel.addComponent(idText);

        /// TODO: 添加修改密码输入框以及修改密码逻辑

        Text oldPasswordText = new Text(33, 7, 8, 1, "旧密码: ");

        Text newPasswordText = new Text(65, 7, 8, 1, "新密码: ");

        InputBox oldPasswordInput = new InputBox(41, 7, 20);
        InputBox newPasswordInput = new InputBox(73, 7, 20);

        rootPanel.addComponent(oldPasswordText);
        rootPanel.addComponent(oldPasswordInput);
        rootPanel.addComponent(newPasswordText);
        rootPanel.addComponent(newPasswordInput);

        // 修改密码按钮
        Button modifyPasswordButton = new Button(50, 9, " 修改密码 ", (button -> {
            UserChangePasswordDTO changePasswordDTO = new UserChangePasswordDTO();
            changePasswordDTO.setUserId(currentUserId);
            changePasswordDTO.setOldPassword(oldPasswordInput.getValue());
            changePasswordDTO.setNewPassword(newPasswordInput.getValue());

            Result<String> stringResult = new UserController().changePassword(changePasswordDTO);
            if (stringResult.getCode() == 1) {
                new LoginAndRegionPanel();
            } else {
                easyTermUI.mount(new TipDialog(40, 15, "修改密码失败"));
            }
        }));
        rootPanel.addComponent(modifyPasswordButton);

        // 退出账号按钮
        Button logoutButton = new Button(4, 9, " 退出账号 ", (button -> {
            LocalCacheUtil.saveToCache("userId", "");
            LocalCacheUtil.saveToCache("role", "0");
            PrintUtils.printAt(0, 0, AnsiConstants.CLEAR_SCREEN);
            new LoginAndRegionPanel();
        }));
        rootPanel.addComponent(logoutButton);
    }




    /**
     * 刷新数据
     */
    private void refresh(int pageNum) {
        borrowPageQueryDTO.setPageNum(pageNum);
        Result<PageResult> pageResultResult = borrowController.selectBorrowList(borrowPageQueryDTO);
        PageResult pageResult = pageResultResult.getData();
        List<BorrowCol> newBorrowCols = convertToBorrowCols(pageResult);
        pagination.setTotal((int) pageResult.getTotal());
        dataTable.setData(newBorrowCols);

        if (init) {
            dataTable.render();
        }
    }

    /**
     * 获取借阅记录列表
     */
    private List<BorrowCol> convertToBorrowCols(PageResult borrowData) {
        List<BorrowCol> borrowCols = new ArrayList<>();
        for (Object borrow : borrowData.getRecords()) {
            BorrowVO libraryBorrow = (BorrowVO) borrow;
            Integer borrowId = libraryBorrow.getBorrowId();
            String bookName = libraryBorrow.getName();
            String borrowTime = libraryBorrow.getBorrowTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String returnTime = libraryBorrow.getReturnTime() == null ? "未归还" : libraryBorrow.getReturnTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            Button returnButton = new Button(0, 0, "归还", (button) -> {
                BorrowVO bindData = (BorrowVO) borrow;
                Integer returnBookId = bindData.getBorrowId();
                Result<String> result = borrowController.revert(((BorrowVO) borrow).getBorrowId());
                if (result.getCode() == 1) {
                    easyTermUI.mountNoAutoStart(new TipDialog(40, 15, "操作成功"));
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    pagination.setCurrentPage(1);
                    refresh(pagination.getCurrentPage());
                } else {
                    easyTermUI.mount(new TipDialog(40, 15, "操作失败"));
                }
                easyTermUI.start();
            });

            BorrowCol borrowCol = new BorrowCol(borrowId, bookName, borrowTime,
                    returnTime,
                    returnButton);
            borrowCols.add(borrowCol);
        }
        return borrowCols;
    }

    /**
     * 生成页码显示文本（当前页/最大页）
     */
    private String getPageInfoText() {
        return pagination.getCurrentPage() + " / " + pagination.getMaxPage();
    }
}
